<?php

namespace Platform\Repository\Organize;

use Illuminate\Http\Request;
use Platform\Models\Organize\LeaderRole;
use Platform\Models\Organize\Organize;
use Platform\Repository\Repository;

class LeaderRoleRepository extends Repository
{

    public function model()
    {
        return  LeaderRole::class;
    }


    public function getOneByName(Organize $organize,$name,$id = null)
    {
        return $organize->role()
            ->where('name', '=', $name)
            ->when($id,function ($query,$id){
                return $query->where('id','<>',$id);
            })
            ->first();
    }

    /**
     * 清空角色默认
     * @param Organize $organize
     */
    public function clearDefault(Organize $organize)
    {
        $organize->role()->where('is_default',LeaderRole::DEFAULT_YES)->update(['is_default' => LeaderRole::DEFAULT_NO]);
    }

    /**
     * 获取默认角色
     * @param Organize $organize
     * @param null $id
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\HasMany|mixed|null|object
     */
    public function getDefault(Organize $organize,$id = null)
    {
        return $organize->role()
            ->where('is_default', LeaderRole::DEFAULT_YES)
            ->when($id, function ($query,$id){
                return $query->where('id','<>',$id);
            })
            ->first();
    }


    /**
     * 通过关键词查询
     * @param Request $request
     * @param Organize $organize
     * @return mixed
     */
    public function screen(Request $request,Organize $organize){
        $builder = $this->model->newQuery();

        $builder->where('organize_id', $organize->id);

        $name = $request->get('name',null);
        $describe = $request->get('describe',null);

        if ($name){
            $builder->where('name', 'like', '%'.$name.'%');
        }
        if ($describe){
            $builder->where('describe', 'like', '%'.$describe.'%');
        }
        $builder->orderByDesc('is_default');

        return $builder->get();
    }

}
